package cn.woblog.android.http;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

import cn.woblog.android.common.utils.MD5;
import cn.woblog.android.common.utils.NetworkUtils;

/**
 * Created by ren on 2015/6/3 0003.
 */
public class CacheConfig implements ICache {

    @Override
    public boolean isCache() {
        return !NetworkUtils.isNetworkAvailable(Http.getContext());
    }

    public String getCacheString(String urlString, String cacheKey) {
        String path = getCacheFilePath(urlString, cacheKey);
        try {
            return FileUtils.readFileToString(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getCacheFilePath(String urlString, String cacheKey) {
        int lastIndexOf = urlString.lastIndexOf("?");
        if (lastIndexOf != -1) {
            urlString = urlString.substring(0, lastIndexOf);
        }
        String filename = MD5.string2MD5((urlString + cacheKey));
        String path = Http.getContext().getCacheDir().getAbsolutePath() + "/" + filename;
        return path;
    }

    public void setCacheString(String urlString, String cacheKey, String data) {
        String path = getCacheFilePath(urlString, cacheKey);
        try {
            FileUtils.writeStringToFile(new File(path), data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
